class AhobEditController
  
  def self.respond_to model, request, config, store
    rlen = request.env['REQUEST_ARRAY'].count
    req = request.env['REQUEST_ARRAY'].slice(1, rlen - 1)
    req[0] = '/' + (req[0] || '')
    key = req.join('/')
    
    # we need to create a new model as the edit model is not required
    model = AModelBanana.new store
    model.load req
    obj = AClockworkBanana.new store, model
    error = []
    saved = false
    if request.env['REQUEST_METHOD'] == 'POST'
      obj.turn key, true
      #TODO: when a field doesn't exist in the model
      request.POST.each do |k, v|
        begin
          obj.send("#{k.to_sym}=", v)
        rescue
          error.push "Received invalid post variable #{k}."
        end
      end
      if obj.is_valid?
        # TODO: error handling
        store.update model, obj, key
        saved = true
      else
        error.concat obj.errors unless obj.is_valid?
      end
    # GET request, just fetch it from the store    
    else
      obj.turn key
    end
    
    # load template and return ('unused' variables *are* used via binding)
    form = load_form model, obj
    title = key
    target = request.env['REQUEST_ARRAY'].join('/')
    response = Rack::Response.new
    response.headers['Content-Type'] = 'text/html'
    response.write ERB.new(store.get_value('/model/AhobEdit/template')).result(binding)
    return response
  end
  
  private

#TODO: centralize this as we use it in edit.rb & add.rb
  def self.load_form model, obj
    form = "<fieldset>\n"
    model.fields.each do |field|
      form << get_input(field, model.fieldtypes[field], obj.send(field.to_sym))
    end
    form << "</fieldset>\n"
  end
  
  def self.get_input field, type, value=''
    res = ''
    case type
      when 'Text'
        res << "  <label for=\"#{field}\">#{field}</label>\n"
        res << "  <textarea name=\"#{field}\" id=\"#{field}\">#{value.split("\r\n").join("\n")}</textarea>\n"
      else
        res << "  <label for=\"#{field}\">#{field}</label>\n"
        res << "  <input type=\"text\" name=\"#{field}\" id=\"#{field}\" value=\"#{value}\" />\n"
    end
    return res
  end
  
end